package download;

import java.io.IOException;

public class DownloadByURL {
    //将指定的资源下载到本地
    public static void download(String url, String path) throws IOException {
        //1. 创建一个URL对象
        java.net.URL u = new java.net.URL(url);
        //2. 通过URL对象，获取一个连接
        java.net.URLConnection con = u.openConnection();
        //3. 通过连接对象，获取一个输入流，用于读取数据
        java.io.InputStream is = con.getInputStream();
        //4. 创建一个文件输出流，用于写入数据
        java.io.FileOutputStream fos = new java.io.FileOutputStream(path);
        //5. 循环读取数据，并写入文件
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        fos.close();
    }
    public static void main(String[] args) throws IOException {
        download("https://img-s.msn.cn/tenant/amp/entityid/AA1QlPa6.img?w=768&h=377&m=6&x=513&y=50&s=68&d=68","2.jpg");
    }
}
